﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Text;

public partial class Admin_Wiki : System.Web.UI.Page
{
    protected int abValue;
    protected int Ancestor = (int)NewsType.Wiki;
    protected string abtext;
    enum Sorting { ByTitle, ByDate, Views };

    protected int CurrentPage;
    Sorting currentSorting;

    protected void Page_Load(object sender, EventArgs e)
    {
        abtext = ab.GetAbText(abValue.ToString());
        if (abtext != string.Empty)
            alefCatLIst.InnerHtml = GetAbLinks(abValue);
        else
            alefCatLIst.InnerHtml = string.Empty;


        if (!Page.IsPostBack)
        {
            GetData();
            fillSubCategoryList();
            MultiViewMain.ActiveViewIndex = 0;
            txtKeywords.Text = PageHeaderData.GetPageKeywordsByType(NewsType.Wiki);
        }
    }

    protected void btnAddKeywords_Click(Object sender, EventArgs e)
    {
        PageHeaderData.SetPageKeywords(NewsType.Wiki, txtKeywords.Text);
    }

    protected void chkVisible_Changed(Object sender, EventArgs e)
    {
        Int32 iLinkID;
        string _val = ((CheckBox)sender).Attributes["CommandArgument"];
        Int32.TryParse(_val, out iLinkID);

        Dal.arParams.Clear();
        Dal.arParams.Add(iLinkID);//PageSize
        Dal.arParams.Add(((CheckBox)sender).Checked);//Checked
        Dal.ExecuteDBsp("Admin_SetVisible", Dal.arParams);

        GetData();
    }

    protected override void OnInit(EventArgs e)
    {
        try
        {
            if (String.IsNullOrEmpty(Request.QueryString["av"]))
                abValue = 1;
            else
                abValue = Convert.ToInt32(Request.Params["av"]);
        }
        catch
        {
            abValue = 1;
        }

        OpenAddCat.Text = ResourceManage.GetString("AddNewEnCyCategorys", "ru");
        btnAddCat.Text = ResourceManage.GetString("Add", "ru");
        lblCname.Text = ResourceManage.GetString("Name", "ru");
        btnBack.Text = ResourceManage.GetString("Back", "ru");
        lblSubDesc.Text = ResourceManage.GetString("Description", "ru");
        lblPageName.Text = "Название страницы";
        base.OnInit(e);
    }

    protected void OpenAddCat_Click(object sender, EventArgs e)
    {
        OpenAddCat.Visible = false;
        MultiViewMain.ActiveViewIndex = 1;
    }

    //private bool isRussionAlfabet(String word)
    //{
    //    Boolean result = false;
    //    List<abItem> dl = ab.GetAbArrayList();

    //    String strBegin;

    //    strBegin = word[0].ToString();
    //    for (int i = 0; i < dl.Count - 1; i++)
    //    {
    //        if (dl[i].abText == strBegin.ToLower())
    //        {
    //            result = true;
    //            break;
    //        }
    //    }
    //    return result;
    //}

    private string GetAbLinks(int _abId)
    {
        // _abId()
        List<abItem> dl = ab.GetAbArrayList();
        if (dl != null)
        {
            StringBuilder strLinks = new StringBuilder();
            strLinks.Append("<ul class=\"alefbetCells\">");
            for (int i = 0; i < dl.Count - 1; i++)
            {
                if (Convert.ToInt32(dl[i].abValue) == _abId)
                {
                    string sText = string.Format("<li><a href=\"Wiki.aspx?av={0}\" class=\"alefbet_s\">{1}</a></li>", dl[i].abValue, dl[i].abText);
                    strLinks.Append(sText);
                }
                else
                {
                    string sText = string.Format("<li><a href=\"Wiki.aspx?av={0}\" class=\"alefbet\">{1}</a></li>", dl[i].abValue, dl[i].abText);
                    strLinks.Append(sText);
                }
            }

            strLinks.Append("</ul>");

            return strLinks.ToString();
        }
        else
            return string.Empty;
    }

    public void fillSubCategoryList()
    {
        List<CategoryItem> keys = Category.ByAncestorsAndAlfabet(Ancestor, abtext);
        if (keys != null)
        {
            GridView1.Visible = true;
            GridView1.DataSource = keys;
            GridView1.DataBind();
        }
        else
        {
            GridView1.Visible = false;
        }
    }

    protected void GridView1_RowCancelingEdit(Object sender, GridViewCancelEditEventArgs e)
    {
        //GridView1.EditIndex = -1;
        //fillSubCategoryList();
    }

    protected void gvNews_PageindexChanging(object sender, GridViewPageEventArgs e)
    {
        CurrentPage = e.NewPageIndex + 1;
        gvNews.PageIndex = e.NewPageIndex;
        GetData();
    }

    protected void btnDeleteSubCat_Click(Object sender, CommandEventArgs e)
    {
        int iCatID;
        Int32.TryParse(e.CommandArgument.ToString(), out iCatID);
        GridView1.EditIndex = -1;
        List<CategoryItem> arr = Category.ByAncestors(iCatID);
        if (arr != null)
        {
            foreach (CategoryItem a in arr)
            {
                Category.Delete(a.catId);
                //PageHeaderData.deleteCategory(a.catId);
            }
        }

        Category.Delete(iCatID);
        //PageHeaderData.deleteCategory(id);
        //fillSubCategoryList();
        String str = ResourceManage.GetString("Exception_SubCatOnDelete", "ru");
        //' lblMsg.Text = 
        //divMsg.Visible = true;
        //divMsgText.Visible = true;
        //divMsgText.InnerText = str.Replace("{0}", id.ToString());
    }

    protected void gvSubs_RowEditing(object sender, GridViewEditEventArgs e)
    {
        GridView1.EditIndex = e.NewEditIndex;
        //fillSubCategoryList();
    }

    protected void btnUpdateSubCat_Click(Object sender, CommandEventArgs e)
    {
        int iCatID;
        Int32.TryParse(e.CommandArgument.ToString(), out iCatID);

        MultiViewMain.ActiveViewIndex = 1;

        TempIDmain = iCatID;
        fillCatsDetailsForView();
    }

    private int _TempIDmain = 0;
    public long TempIDmain
    {
        get
        {
            if (this.ViewState["_TempIDmain"] == null)
                return _TempIDmain;
            else
                return (long)ViewState["_TempIDmain"];
        }
        set
        {
            this.ViewState["_TempIDmain"] = value;
        }
    }

    private void fillCatsDetailsForView()
    {
        //cleareDetailsView();
        CategoryItem keys = Category.ItemById((int)TempIDmain);
        if (keys != null)
        {
            txtCatname.Text = keys.cTitle;
            txtcDesc.Text = keys.cDescription;
            txtPageName.Text = keys.cPageName;
        }
    }

    //private void cleareDetailsView()
    //{
    //    lblDcTitle.Text = string.Empty;
    //    lblDcDesc.Text = string.Empty;
    //    lblDPhtml.Text = string.Empty;
    //    lblDMdescription.Text = string.Empty;
    //    lblDMkeywords.Text = string.Empty;
    //    lblDMrobots.Text = string.Empty;
    //    lblDMTitle.Text = string.Empty;
    //}

    protected void btnAddCat_Click(object sender, EventArgs e)
    {

        //if (!isRussionAlfabet(txtCatname.Text))
        //{
        //    divMsg.Visible = true;
        //    divMsgText.Visible = true;
        //    String str = ResourceManage.GetString("Exception_NotRussionAlfabet", "ru");
        //    divMsgText.InnerHtml = str;
        //    return;
        //}

        string sText = txtCatname.Text;
        string sPagename = (txtPageName.Text.Trim().Length>0)?txtPageName.Text.Trim():sText;
        
        Dal.arParams.Clear();
        Dal.arParams.Add(TempIDmain);
        Dal.arParams.Add(Ancestor); // med centers
        Dal.arParams.Add(sText);
        Dal.arParams.Add(txtcDesc.Text);
        Dal.arParams.Add(ab.ConvertToEnglishText(sPagename));
        Dal.arParams.Add(1);
        Dal.ExecuteDBsp("Admin_AddCategory", Dal.arParams, true);
        //GetCategories();

        //int id = Category.Insert(Ancestor, txtCatname.Text, ab.ConvertToEnglishText(txtCatname.Text));

        string word = txtCatname.Text.TrimStart().ToLower();
        string tes = word[0].ToString();
        string ret = ab.GetAbValue(tes);
        clearFeilds();
        fillSubCategoryList();
        MultiViewMain.ActiveViewIndex = 0;
        //Response.Redirect("EnCategorys.aspx?av=" + ret);
    }

    protected void btnBack_Click(object sender, EventArgs e)
    {
        OpenAddCat.Visible = true;
        MultiViewMain.ActiveViewIndex = 0;
        fillSubCategoryList();
    }

    private void clearFeilds()
    {
        txtCatname.Text = string.Empty;
        txtcDesc.Text = string.Empty;
        txtPageName.Text = string.Empty;
    }

    protected void btnDeleteNews_Click(Object sender, CommandEventArgs e)
    {
        Int32 iLinkID;
        Int32.TryParse(e.CommandArgument.ToString(), out iLinkID);

        Dal.arParams.Clear();
        Dal.arParams.Add(iLinkID);
        Dal.ExecuteDBsp("Admin_DeleteArticle", Dal.arParams);
        GetData();
    }

    protected void btnEditNews_Click(Object sender, CommandEventArgs e)
    {
        Int32 iLinkID;

        Int32.TryParse(e.CommandArgument.ToString(), out iLinkID);

        Response.Redirect("Addarticle.aspx?id=" + iLinkID);
    }

    protected void gvNews_Sorting(object sender, GridViewSortEventArgs e)
    {
        switch (e.SortExpression)
        {
            case "Title":
                currentSorting = Sorting.ByTitle;
                break;
            case "Date":
                currentSorting = Sorting.ByDate;
                break;
            case "Views":
                currentSorting = Sorting.Views;
                break;
        }
        GetData();
    }

    private void GetData()
    {
        ObjectDataSource ods = new ObjectDataSource();
        ods.ID = "ods" + 1;
        ods.EnablePaging = gvNews.AllowPaging; //the paging of ODS depends on the paging of the GridView
        ods.TypeName = "MyTableAdapter"; //be sure to prefix the namespace of your application !!! e.g. MyApp.MyTableAdapter

        ods.SelectMethod = "GetData";
        ods.SelectCountMethod = "VirtualItemCount";
        ods.StartRowIndexParameterName = "startRow";
        ods.MaximumRowsParameterName = "maxRows";
        ods.EnableViewState = false;

        ods.ObjectCreating += new ObjectDataSourceObjectEventHandler(ods_ObjectCreating);
        try
        {
            gvNews.DataSource = ods;
            gvNews.DataBind();
        }
        catch { }
        //if (ddlPageNumber.Items.Count == 0 || GVTrivias.PageCount != ddlPageNumber.Items.Count)
        //{
        //    ddlPageNumber.Items.Clear();
        // for (int icount = 1; icount < gvNews.PageCount + 1; icount++)
        //   {
        ////        ListItem li = new ListItem(icount.ToString(), icount.ToString());
        ////        ddlPageNumber.Items.Add(li);
        //    }
        //    lblShowRecords.Text = string.Format(" {0} ", GVTrivias.PageCount);
        //}

    }

    private void ods_ObjectCreating(object sender, ObjectDataSourceEventArgs e)
    {
        //calling a "parametered" constructor of my own TableAdapter and passing it to the ObjectInstance property 
        Dal.arParams.Clear();
        Dal.arParams.Add((int)NewsType.Wiki);//CatID
        Dal.arParams.Add(CurrentPage);//Current Page
        Dal.arParams.Add(gvNews.PageSize);//PageSize
        Dal.arParams.Add((int)currentSorting);//PageSize
        Dal.arParams.Add(abtext);//PageSize
        DataTable DT = Dal.ExecuteDBsp("Admin_GetWikiByCategoryWPaging", Dal.arParams,true);

        if (DT != null)
        {
            if (DT.Rows.Count > 0)
            {
                MyTableAdapter tAdapter = new MyTableAdapter(DT);
                e.ObjectInstance = tAdapter;
            }
            //and that'all there's to it !!
        }
    }

    // Delete Confirm
    protected void GridView1_RowBound(object sender, GridViewRowEventArgs e)
    {
        try
        {
            Admin_WikiSubCats SubCats = (Admin_WikiSubCats)e.Row.FindControl("SubCats1");
            SubCats.fillSubCategoryList();
        }
        catch { }
        AjaxControlToolkit.ConfirmButtonExtender cb = new AjaxControlToolkit.ConfirmButtonExtender();
        try
        {
            Button btn=(Button)e.Row.FindControl("lnkDeleteww");
         
            
            Int32 iCatID;
            Int32.TryParse(btn.CommandArgument.ToString(), out iCatID);

            cb.TargetControlID = btn.ClientID.Replace("_", "$");
            cb.OnClientCancel = "CancelClick";
            cb.ConfirmText = string.Format("Вы уверены , что хотите удалить запись {0} ?",Category.ItemById(iCatID).cTitle);
            e.Row.Cells[1].Controls.Add(cb);
        }
        catch { }
    }

    protected void gvNews_RowBound(object sender, GridViewRowEventArgs e)
    {
        AjaxControlToolkit.ConfirmButtonExtender cb = new AjaxControlToolkit.ConfirmButtonExtender();
        try
        {
            cb.TargetControlID = e.Row.FindControl("btnDeleteNews").ClientID.Replace("_", "$");
            cb.OnClientCancel = "CancelClick";
            cb.ConfirmText = "Вы уверены , что хотите удалить запись ?";
            e.Row.Cells[5].Controls.Add(cb);
        }
        catch { }
    }
}
